import toml
from pathlib import Path
import game

class LANG_:
    _DIR = Path("lang/")
    _DEFAULT = None
    _USE = None

def __path(names:tuple, langmap:dict) -> str:
    node = langmap
    for k in names:
        node = node.get(k)
        if node is None:
            return ""
    return node if isinstance(node, str) else ""

def __replace_for_table(text:str, table:dict) -> str:
    for k,v in table.items():
        text = text.replace(f"[[{k}]]", str(v))
    return text

def path(*names, **replaces) -> str:
    text = __path(names, LANG_._USE)
    if LANG_._USE is LANG_._DEFAULT:
        return __replace_for_table(text, replaces)
    return __replace_for_table(__path(names, LANG_._DEFAULT), replaces)

def usable() -> bool:
    pass

def use(id:str) -> bool:
    path = Path(LANG_._DIR, f"{id}.toml")
    if path.is_file():
        root = toml.loads(path.read_text("utf-8"))
        if isinstance(root, dict):
            LANG_._USE = root
            return True
    return False

def init_by_main_use_only(id_for_default_lang:str) -> bool:
    if use(id_for_default_lang):
        LANG_._DEFAULT = LANG_._USE
        return True
    return False

def piece_name(piece:int) -> str:
    return path("token", ("piece-black" if (piece == game.P_BLACK) else "piece-white"))

_SHAPEMAP = {
    game.Shape.D1: "shape-d1",
    game.Shape.D2: "shape-d2",
    game.Shape.D3: "shape-d3",
    game.Shape.D4: "shape-d4",
    game.Shape.S1: "shape-s1",
    game.Shape.S2: "shape-s2",
    game.Shape.S3: "shape-s3",
    game.Shape.S4: "shape-s4",
    game.Shape.S44: "shape-s44",
    game.Shape.L1: "shape-l1",
    game.Shape.L2: "shape-l2",
    game.Shape.L3: "shape-l3",
    game.Shape.L4: "shape-l4",
    game.Shape.L5: "shape-l5",
    game.Shape.LONG: "shape-long",
}
def shape_name(shape_max:int) -> str:
    return path("token", _SHAPEMAP.get(shape_max, "shape-d1"))

def time_by_second(second:int) -> str:
    if second >= 3600:
        hours = second // 3600
        remain = second % 3600
        return f"{hours}{path('token','time-hour')}{time_by_second(remain) if (remain > 0) else ''}"
    elif second >= 60:
        minutes = second // 60
        remain = second % 60
        return f"{minutes}{path('token','time-minute')}{time_by_second(remain) if (remain > 0) else ''}"
    elif second > 0:
        return f"{second}{path('token','time-second')}"
    else:
        return path("token","time-off")
